// store/index.ts
import { defineStore } from "pinia";
import { menuData } from "../interface/index";
import router from "../router/index";
import { ElMessage } from "element-plus";
import { RouteRecordRaw } from "vue-router";

interface Layout {
  menuData: menuData[] ;
}
// layout 相关
export const layout = defineStore("layout", {
  state: (): Layout => ({
    menuData: [],
  }),
  actions: {
    setMenuData(item: []){
      console.log(item)
      this.menuData = item 
    }
  },
  getters: {
    getMenu(state) {
      return state.menuData;
    },
  },
});

// tab切换相关
export const tabs = defineStore("tabs", {
  state: () => ({
    tabList: [] as menuData[],
    current: "",
    keeps:[] as string[]
  }),
  actions: {
    // 新增或者切换tab 
    changeTabs(item: menuData) {
      let tab = this.tabList.find( (v: menuData) =>{
        return v.path == item.path;
      });
      if (!tab) {
        this.tabList.push(item);
        this.keeps.push(item.component)
      }
      this.current = item.path;
    },
    // 删除Tab同时将Keepalive设置为false
    delTabs(item: menuData) {
      const currentRouter = router.currentRoute;
      if (this.tabList.length === 1) {
        return ElMessage.error("不允许删除所有的tab");
      }
      // 判断当前路由
      if (item.path === currentRouter.value.path) {
          let next = {} as menuData
          const index = this.tabList.findIndex((v) => v.path === item.path);
          if(index===0){
            next = this.tabList[1]
          }else{
            next = this.tabList[index-1]
          }
          this.current = next.path
          router.push(next.path)
      }
      this.tabList = this.tabList.filter(v=>v.path!==item.path)
      this.keeps = this.keeps.filter(v=>v!==item.component)
      console.log(this.keeps)
    },
    setDefault(item:menuData[],path:string){
      let temp =getDefault(item,path)
      this.tabList =[temp]
      this.keeps =[temp.component]
      this.current = temp.path
    },
    
  },
  getters: {
    getTabs(state) {
      return state.tabList;
    },
    getCurrent(state) {
      return state.current;
    },
    getKeeps():string{
      console.log(this.keeps.join(','))
      return this.keeps.join(',')
    }
  },
});

// 获取当前的路由
function getCurrentRoute(item: menuData): RouteRecordRaw {
  let routes = router.getRoutes(); // 获取所有的routes
  let currentRoutes = {} as RouteRecordRaw; // 定义当前的route
  currentRoutes = routes.find((v) => v.path === item.path) as RouteRecordRaw;
  return currentRoutes;
}
// 判根据传入的item获取是否为当前的路由
function getDefault(item:menuData [],path:string):menuData{
  let temp:menuData = item[0]
  item.forEach(v=>{
    if(v.path===path){
      temp = v
    }else if(v.children && v.children.length>0){
      temp = getDefault(v.children,path)
    }
  })
  return temp
}

